<template>
  <div class="main app-container">
    <!-- 顶部查询表单 -->
    <div>
      <el-form :model="queryParam" label-position="right" label-width="100px" ref="searchFrom" size="mini" inline>
        <el-form-item label="订单编号：" prop="code">
          <el-input clearable size="mini" style="width: 200px" v-model="queryParam.code"></el-input>
        </el-form-item>
        <el-form-item label="委托书编号：" prop="code">
          <el-input clearable size="mini" style="width: 200px" v-model="queryParam.cmtNo"></el-input>
        </el-form-item>
        <el-form-item label="订单状态：">
          <el-select clearable filterable style="width: 200px" v-model="queryParam.status">
            <el-option :key="index" :label="item.rvCmeaning" :value="item.rvLowValue" v-for="(item, index) in attStatus"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="结算状态：" prop="attBillStatus">
          <el-select clearable size="mini" style="width: 200px" v-model="queryParam.billAttStatus">
            <el-option v-for="(item, key, index) in billAttStatus" :key="index" :label="item" :value="key"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="下单时间：">
          <el-date-picker placeholder="选择日期" size="mini" style="width: 200px" type="datetime" v-model="queryParam.startTime"></el-date-picker>
          -
          <el-date-picker placeholder="选择日期" size="mini" style="width: 200px" type="datetime" v-model="queryParam.endTime"></el-date-picker>
        </el-form-item>
        <el-form-item label-width="0">
          <el-button @click="initOrderTable" size="mini" type="primary">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="title">订单列表</div>
    <div class="bottons">
      <buttonName @clickEvent="clickEvent"></buttonName>
    </div>
    <div style="margin-top: 10px">
      <el-form :model="statisticsFrom" size="mini" :inline="true">
        <el-form-item label="总金额：" prop="totalAmount">
          <el-input disabled v-model="statisticsFrom.totalAmount" style="width: 150px"></el-input>
        </el-form-item>
        <el-form-item label="已结算金额：" prop="settledAmount">
          <el-input disabled v-model="statisticsFrom.settledAmount" style="width: 150px"></el-input>
        </el-form-item>
        <el-form-item label="未结算金额：" prop="settleAmount">
          <el-input disabled v-model="statisticsFrom.settleAmount" style="width: 150px"></el-input>
        </el-form-item>
      </el-form>
    </div>
    <split-pane :default-percent="65" :min-percent="20" split="horizontal" style="height:75%" v-on:resize="resize">
      <template slot="paneL">
        <!-- 订单列表 -->
        <div ref="orderTableRef" style="height:85%">
          <el-table
            :data="orderTable.data"
            :header-cell-style="{ textAlign: 'center' }"
            :height="orderTableHeight"
            @row-click="orderTableRowClick"
            border
            highlight-current-row
            style="width:100%"
          >
            <el-table-column align="center" label="序号" type="index" width="50"></el-table-column>
            <el-table-column align="center" prop="billAttStatus" label="结算状态" show-overflow-tooltip width="180">
              <template slot-scope="scope">
                {{ billAttStatus[scope.row.billAttStatus] }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="订单状态" prop="attStatusName" show-overflow-tooltip width="180"></el-table-column>
            <el-table-column align="center" label="委托书编号" prop="cmtNo" show-overflow-tooltip width="180"></el-table-column>
            <el-table-column align="center" label="订单号" prop="attCode" show-overflow-tooltip width="160"></el-table-column>
            <el-table-column align="center" label="客户名称" prop="adcConsigner" show-overflow-tooltip width="160"></el-table-column>
            <el-table-column align="center" label="起始地" prop="adcSAddress" show-overflow-tooltip width="200"></el-table-column>
            <el-table-column align="center" label="目的地" prop="adcDAddress" show-overflow-tooltip width="200"></el-table-column>
            <el-table-column align="center" label="货物名称" prop="gdsNames" show-overflow-tooltip width="160"></el-table-column>
            <el-table-column align="center" label="已派车量" prop="dispatch" show-overflow-tooltip width="160"></el-table-column>
            <el-table-column align="center" label="未派车量" prop="ndispatch" show-overflow-tooltip width="160"></el-table-column>
            <el-table-column align="center" label="总金额" prop="totalAmount" show-overflow-tooltip width="160"></el-table-column>
            <el-table-column align="center" label="已结算金额" prop="settledAmount" show-overflow-tooltip width="160"></el-table-column>
            <el-table-column align="center" label="未结算金额" prop="settleAmount" show-overflow-tooltip width="160"></el-table-column>
            <el-table-column align="center" label="审核人" prop="attAuditor" show-overflow-tooltip width="160"></el-table-column>
            <el-table-column align="center" label="审核时间" prop="attAudittime" show-overflow-tooltip width="180"></el-table-column>
            <el-table-column align="center" label="备注" prop="attRemark" show-overflow-tooltip width="180"></el-table-column>
          </el-table>
          <div class="block">
            <el-pagination
              :current-page="Pagination.currentPage"
              :layout="Pagination.layout"
              :page-size="Pagination.PageSize"
              :page-sizes="Pagination.pageSizeList"
              :total="Pagination.total"
              @current-change="handleCurrentChange"
              @size-change="handleSizeChange"
              background
              class="pagination"
              ref="pagination"
              small
            ></el-pagination>
          </div>
        </div>
      </template>
      <template slot="paneR">
        <!-- 运单列表 -->
        <div ref="wayTableHRef" style="height:85%">
          <el-table
            :data="wayTable.data"
            :header-cell-style="{ textAlign: 'center' }"
            :height="wayTableHeight"
            :row-key="wayTableRowKey"
            @row-click="wayTableClick"
            @selection-change="waySelectionChange"
            @select="wayTableSelect"
            @select-all="wayTableSelect"
            border
            highlight-current-row
            ref="wayTableRef"
            style="width:100%"
          >
            <el-table-column align="center" label="序号" type="index" width="50"></el-table-column>
            <el-table-column :fixed="true" :selectable="wayTableSelectable" align="center" type="selection"></el-table-column>
            <el-table-column align="center" label="结算状态" show-overflow-tooltip sortable width="150">
              <template slot-scope="scope">
                <span>{{ settlementStatus[scope.row.isSettlement] }}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="运单状态" prop="wayStatusName" show-overflow-tooltip sortable width="150"></el-table-column>
            <el-table-column align="center" label="运单号" prop="wabCode" show-overflow-tooltip sortable width="200"></el-table-column>
            <el-table-column align="center" label="车牌号" prop="wayTrkNo" show-overflow-tooltip sortable width="150"></el-table-column>
            <el-table-column align="center" label="司机" prop="dvrName" show-overflow-tooltip sortable width="150"></el-table-column>
            <el-table-column align="center" label="司机电话" prop="wayTrkNo" show-overflow-tooltip sortable width="150"></el-table-column>
            <el-table-column align="center" label="货物名称" prop="wayGoodName" show-overflow-tooltip sortable width="150"></el-table-column>
            <el-table-column align="center" label="货物重量(T)" prop="wayWeight" show-overflow-tooltip sortable width="150"></el-table-column>
            <el-table-column align="center" label="箱号" prop="wabCtrNo" show-overflow-tooltip sortable width="150"></el-table-column>
            <el-table-column align="center" label="铅封号" prop="wabSealNo" show-overflow-tooltip sortable width="150"></el-table-column>
            <el-table-column align="center" label="生产批次" prop="wabProBatch" show-overflow-tooltip sortable width="180"></el-table-column>
            <el-table-column align="center" label="装货时间" prop="wcdSttime" show-overflow-tooltip sortable width="180"></el-table-column>
            <el-table-column align="center" label="卸货时间" prop="wcdEdtime" show-overflow-tooltip sortable width="180"></el-table-column>
          </el-table>
          <el-dialog
            v-el-drag-dialog
            ref="dialog"
            width="600px"
            :modal-append-to-body="false"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            :visible.sync="showDialog"
            v-if="showDialog"
            :title="operate"
            :before-close="handleClose"
          >
            <el-form :model="dialogForm" ref="dialogForm" label-width="13rem" size="mini" :rules="dialogFormRules">
              <el-row>
                <el-col :span="18">
                  <el-form-item label="费目名称：" prop="fyName">
                    <el-select v-model="dialogForm.fyName" placeholder="请选择" clearable filterable style="width:100%">
                      <el-option v-for="item in feiyongList" :key="item.rvLowValue" :label="item.rvCmeaning" :value="item.rvLowValue"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="18">
                  <el-form-item label="单价：" prop="unitprice">
                    <el-input
                      minlength="1"
                      maxlength="10"
                      :oninput="(dialogForm.unitprice = numberOnly(dialogForm.unitprice))"
                      v-model="dialogForm.unitprice"
                      clearable
                      @change="dototalprice"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="18">
                  <el-form-item label="运输量：" prop="trafficweight">
                    <el-input
                      minlength="1"
                      maxlength="10"
                      :oninput="(dialogForm.trafficweight = numberOnly(dialogForm.trafficweight))"
                      v-model="dialogForm.trafficweight"
                      @change="dototalprice"
                      clearable
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="18">
                  <el-form-item label="费用（总价）：" prop="totalprice">
                    <el-input minlength="1" maxlength="10" v-model="dialogForm.totalprice" clearable></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item prop="remark" label="备注：">
                    <el-input maxlength="32" type="textarea" v-model="dialogForm.remark" clearable></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button size="mini" @click="close('dialogForm')">关闭</el-button>
              <el-button size="mini" @click="save" type="primary">保存</el-button>
            </div>
          </el-dialog>
        </div>
      </template>
    </split-pane>
  </div>
</template>

<script>
import buttonName from '@/components/buttonName/button-name'
import pagination from '@/mixins/pagination'
import resize from '@/mixins/resize'
import { addChargeBill, queryBillAtt, queryBillWay } from '@/request/api'
import { getRefCodesByType } from '@/request/dropDown'
import { accAdd } from '@/utils/utils'
import store from '@/store'

export default {
  mixins: [pagination, resize],
  data() {
    return {
      statementData: {}, //结算单信息
      feiyongList: [],
      dialogFormRules: {
        fyName: [{ required: true, message: '费目名称不能为空', trigger: 'blur' }],
        unitprice: [{ required: true, message: '单价不能为空,可填0', trigger: 'blur' }],
        trafficweight: [{ required: true, message: '运输量不能为空', trigger: 'blur' }],
        totalprice: [{ required: true, message: '总价不能为空', trigger: 'blur' }]
      },
      billAttStatus: {
        W: '未生成',
        Y: '已生成',
        B: '部分生成'
      },
      dialogForm: {
        fyName: '',
        unitprice: '',
        trafficweight: '',
        totalprice: '',
        remark: ''
      },
      operate: '',
      showDialog: false,
      attStatus: [],
      selectList: [],
      settlementStatus: {
        Y: '已生成',
        N: '未生成'
      },
      orderTableHeight: -1,
      wayTableHeight: -1,
      currentData: {},
      queryParam: {
        status: '',
        code: '',
        cmtNo: '',
        startTime: undefined,
        endTime: undefined,
        billAttStatus: ''
      },
      orderTable: {
        data: []
      },
      wayTable: {
        data: []
      },
      genSource: 'pt',
      statisticsFrom: {
        totalAmount: 0,
        settledAmount: 0,
        settleAmount: 0
      }
    }
  },
  components: {
    buttonName
  },
  created() {
    this.resize = () => {
      this.orderTableHeight = this.$refs.orderTableRef.offsetHeight
      this.wayTableHeight = this.$refs.wayTableHRef.offsetHeight
    }
  },
  mounted() {
    this.initOrderTable()
    getRefCodesByType('费用类型').then(ref => {
      console.log(ref.data)
      this.feiyongList = ref.data

      for (let i = this.feiyongList.length - 1; i >= 0; i--) {
        if (this.feiyongList[i].rvLowValue === 'SHIP' || this.feiyongList[i].rvLowValue === 'INFO') {
          this.feiyongList.splice(i, 1)
        }
      }
    })
  },
  methods: {
    numberOnly(data) {
      if (data == null) {
        return null
      }
      let val = data.toString().replace(/(^\s*)|(\s*$)/g, '')
      if (!val) {
        return val
      }
      val = val.replace(/[^\d.]/g, '')
      // 保证第一位只能是数字，不能是点
      val = val.replace(/^\./g, '')
      // 小数只能出现1位
      val = val
        .replace('.', '$#$')
        .replace(/\./g, '')
        .replace('$#$', '.')
      // 小数点后面保留2位
      val = val.replace(/^(\-)*(\d+)\.(\d\d\d\d).*$/, '$1$2.$3')
      return val
    },
    dototalprice() {
      let val = parseFloat(this.dialogForm.unitprice || 0)
      this.dialogForm.totalprice = (this.dialogForm.trafficweight * val).toFixed(2)
    },
    close(formName) {
      this.$refs[formName].clearValidate()

      this.showDialog = false
    },
    handleClose(done) {
      if (this.$refs.dialogForm) {
        this.$refs.dialogForm.clearValidate()
        done()
      }
    },
    // 初始化订单表
    initOrderTable() {
      queryBillAtt({
        index: this.Pagination.currentPage,
        size: this.Pagination.pageSize,
        code: this.queryParam.code,
        startTime: this.queryParam.startTime,
        endTime: this.queryParam.endTime,
        status: this.queryParam.status,
        cmtNo: this.queryParam.cmtNo,
        billAttStatus: this.queryParam.billAttStatus,
        source: 2
      }).then(res => {
        this.orderTable.data = res.data.billOrderVOS
        this.statisticsFrom = res.data
        this.updatePaginationTotal(res.total)
      })
    },
    // 初始化运单
    initWayTable() {
      queryBillWay({
        attId: this.currentData.attId,
        source: 2
      }).then(res => {
        this.wayTable.data = res.data
        if (this.wayTable.data.length != 0) {
          this.wayTable.data.forEach(w => {
            if (w.isSettlement == 'Y') {
              this.$nextTick(() => {
                this.$refs.wayTableRef.toggleRowSelection(w)
              })
            }
          })
        }
      })
    },
    initOrderStatus() {
      getRefCodesByType('网络平台订单状态').then(res => {
        this.attStatus = res.data
      })
    },
    getList() {
      this.initOrderTable()
    },
    //生成自定义结算单
    customize() {
      if (Object.keys(this.statementData).length === 0) {
        window._$message.error('请至少选择一项')
        return
      }
      this.showDialog = true
      this.operate = '自定义费用'
    },
    save() {
      this.$refs.dialogForm.validate(valid => {
        if (valid) {
          const l = []
          l.push({
            cbiAttId: this.currentData.attId,
            cbiCmtId: this.currentData.cmtId,
            cbiWayId: this.statementData.wayId,
            cbiLoadingGoodsTime: this.statementData.wcdSttime,
            cbiLoadingGoodsPlace: this.statementData.wabPlaceof,
            cbiUnloadGoodsPlaceL: this.statementData.wabReceplace,
            cbiGoodName: this.statementData.wayGoodName,
            cbiTrkNo: this.statementData.wayTrkNo,
            cbiDriverName: this.statementData.dvrName,
            cbiPrice: this.statementData.price,
            cbiTotalPrice: this.statementData.total,
            cbCtrNo: this.statementData.wabCtrNo,
            cbSealNo: this.statementData.wabSealNo,
            cbiGenSource: this.statementData.genSource
          })

          addChargeBill({
            cbNo: this.currentData.cmtNo,
            cbBillCmtId: this.currentData.cmtId,
            cbBillName: '结算单',
            cbBillStatus: '1',
            cbPrice: this.dialogForm.unitprice,
            cbBillTotal: this.dialogForm.totalprice,
            cbIsDel: 0,
            cbBillType: this.dialogForm.fyName,
            cbJpayer: this.currentData.cmtPartyA,
            payA: this.currentData.cmtPartyA,
            payB: this.currentData.cmtPartyB,
            itemDTOList: l,
            cbWeight: this.dialogForm.trafficweight,
            cbType: this.currentData.transportMode == 'DS' ? 'sea' : 'way',
            cbBillAttId: this.currentData.attId,
            cbFltId: store.state.user.FLT_UUID_DX_H,
            genSource: this.genSource,
            cbRemark: this.dialogForm.remark
          }).then(() => {
            window._$message.success('成功')
            this.showDialog = false
            this.initOrderTable()
            this.clearData()
          })
        }
      })
    },
    // 生成结算单
    genBill() {
      if (this.selectList.length === 0) {
        window._$message.error('请至少勾选一项')
        return
      }
      const l = []
      // 总吨数
      let totalWeight = 0
      // 总金额
      let totalAmount = 0
      this.selectList.forEach(v => {
        totalWeight = accAdd(totalWeight, v.wabWeight)
        totalAmount = accAdd(totalAmount, v.total)
        l.push({
          cbiAttId: this.currentData.attId,
          cbiCmtId: this.currentData.cmtId,
          cbiWayId: v.wayId,
          cbiLoadingGoodsTime: v.wcdSttime,
          cbiLoadingGoodsPlace: v.wabPlaceof,
          cbiUnloadGoodsPlaceL: v.wabReceplace,
          cbiGoodName: v.wayGoodName,
          cbiTrkNo: v.wayTrkNo,
          cbiDriverName: v.dvrName,
          cbiPrice: v.price,
          cbiTotalPrice: v.total,
          cbCtrNo: v.wabCtrNo,
          cbSealNo: v.wabSealNo,
          cbiGenSource: this.genSource
        })
      })
      addChargeBill({
        cbNo: this.currentData.cmtNo,
        cbBillCmtId: this.currentData.cmtId,
        cbBillName: '结算单',
        cbBillStatus: '1',
        cbPrice: this.currentData.price,
        cbBillTotal: totalAmount,
        cbIsDel: 0,
        cbBillType: 'SHIP',
        cbJpayer: this.currentData.cmtPartyA,
        payA: this.currentData.cmtPartyA,
        payB: this.currentData.cmtPartyB,
        itemDTOList: l,
        cbWeight: totalWeight,
        cbType: this.currentData.transportMode == 'DS' ? 'sea' : 'way',
        cbBillAttId: this.currentData.attId,
        cbFltId: store.state.user.FLT_UUID_DX_H,
        genSource: this.genSource
      }).then(() => {
        window._$message.success('成功')
        this.initOrderTable()
        this.clearData()
      })
    },
    // 取消生成
    cancel() {},
    // 订单表点击
    orderTableRowClick(val) {
      this.currentData = val
      this.selectList = []
      this.initWayTable()
    },
    wayTableRowKey(val) {
      return val.wayId
    },
    wayTableClick(row) {
      if (row.isSettlement === 'Y') {
        this.$message.error({
          showClose: true,
          message: '请选择未结算的运单'
        })
        return
      }
      this.$refs['wayTableRef'].toggleRowSelection(row)
      this.statementData = row
    },
    wayTableSelectable(val) {
      return val.isSettlement === 'N'
    },
    clearData() {
      this.currentData = {}
      this.statementData = {}
      this.dialogForm = {
        fyName: '',
        unitprice: '',
        trafficweight: '',
        totalprice: '',
        remark: ''
      }
      this.selectList = []
      this.wayTable.data = []
    },
    clickEvent(val) {
      if (val.mdlCode === 'settlementPGen') {
        this.genBill()
      }
      if (val.mdlCode === 'customize') {
        this.customize()
      }
    },
    waySelectionChange(val) {
      this.selectList = []
      for (let item of val) {
        if (item.isSettlement === 'N') {
          this.selectList.push(item)
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.title {
  font-size: 15px;
}

.bottons {
  margin-top: 10px;
  margin-bottom: 10px;
}
</style>
